package com.quanyan.stadium.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.place.entity.apiresp.RespCity;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.stadium.api.req.ReqCategoryPriority;
import com.quanyan.stadium.api.req.ReqCategoryPriorityList;
import com.quanyan.stadium.api.req.ReqUserRadarChart;
import com.quanyan.stadium.api.resp.RespGameSportCardData;
import com.quanyan.stadium.api.resp.RespUserCategoryList;
import com.quanyan.stadium.api.resp.RespUserCategoryVo;
import com.quanyan.stadium.biz.BizSportCardDao;
import com.quanyan.stadium.component.cache.MyRedisTemplate;
import com.quanyan.stadium.component.cache.StadiumRedisConstants;
import com.quanyan.stadium.constants.GameConstants;
import com.quanyan.stadium.entity.TbGameCategoryUser;
import com.quanyan.stadium.entity.TbGameCategoryUserExample;
import com.quanyan.stadium.entity.TbUserGameCollect;
import com.quanyan.stadium.entity.TbUserGameCollectExample;
import com.quanyan.stadium.entity.vo.CategoryPriority;
import com.quanyan.stadium.entity.vo.UserGrade;
import com.quanyan.stadium.entity.vo.UserGradeIntegral;
import com.quanyan.stadium.mapper.TbGameCategoryUserMapper;
import com.quanyan.stadium.mapper.TbUserGameCollectMapper;
import com.quanyan.stadium.service.*;
import com.quanyan.stadium.service.commonComponent.BaseService;
import com.quanyan.user.response.RespUserInfoDetail;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author dongshenglin
 * @date 2016/6/30  11:18
 */
@Service
public class SportCardServiceImpl implements SportCardService {

    @Autowired
    private TbGameCategoryUserMapper tbGameCategoryUserMapper;

    @Autowired
    private TbUserGameCollectMapper tbUserGameCollectMapper;
    @Autowired
    private RadarChartService radarChartService;

    @Autowired
    private BizSportCardDao bizSportCardDao;

    @Autowired
    private GradeIntegralService gradeIntegralService;

    @Autowired
    private StadiumIndexService stadiumIndexService;

    @Autowired
    private BaseService baseService;

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(SportCardServiceImpl.class);

    @Override
    public APIResponse initSportCard(Integer userId) {
        if (null == userId){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        int changeRow = 0;
        List<TbGameCategoryUser> tbGameCategoryUserList = this.getGameCategoryUser(userId);
        if (tbGameCategoryUserList.size() == 0){
            int categoryNum = GameConstants.CATEGORY_NUM;
            TbGameCategoryUser tbGameCategoryUser = new TbGameCategoryUser();
            tbGameCategoryUser.setUid(userId);
            tbGameCategoryUser.setLevel(0);
            tbGameCategoryUser.setIsObtain((byte) 1);
            tbGameCategoryUser.setIsDelete((byte) 0);
            for (Integer i = 1; i <= categoryNum; i++){
                tbGameCategoryUser.setGameCategoryId(i);
                tbGameCategoryUser.setPriority(i);
                changeRow += tbGameCategoryUserMapper.insertSelective(tbGameCategoryUser);
            }
        }
        return APIResponse.returnSuccess(changeRow);
    }

    @Override
    public APIResponse<RespUserCategoryList> getUserCategoryList(Integer userId) {
        //借助redis特性处理并发
        RedisKey redisKey = new RedisKey(RedisConstants.STADIUM_FAMILY_KEY, StadiumRedisConstants.getUserSportCard(userId));
        long recordFlag = myRedisTemplate.setnx(redisKey);
        if (recordFlag == 0) {
            myRedisTemplate.delteKey(redisKey);
            return APIResponse.returnSuccess();
        }
        if (null == userId){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        RespUserCategoryList respUserCategoryList = new RespUserCategoryList();
        List<RespUserCategoryVo> categoryVoList = bizSportCardDao.getUserCategoryList(userId);
        if (null != categoryVoList && categoryVoList.size() > 0){
            respUserCategoryList.setRespUserCategoryList(categoryVoList);
        }
        if (null == categoryVoList || categoryVoList.size() == 0){
             this.initSportCard(userId);
            List<RespUserCategoryVo> categoryList = bizSportCardDao.getUserCategoryList(userId);
            if (null != categoryList && categoryList.size() > 0){
                respUserCategoryList.setRespUserCategoryList(categoryList);
            }
        }

        /**
         * 获取用户信息（头像、昵称、城市、性别）
         */
        RespUserInfoDetail userInfoDetail = baseService.queryUserMsg(userId);
        if(null != userInfoDetail){
            respUserCategoryList.setUserName(userInfoDetail.getNickName());
            respUserCategoryList.setIconUrl(userInfoDetail.getIcon());
            respUserCategoryList.setSex(userInfoDetail.getGender());
            /**
             * 用户所在城市
             */
            RespCity city =  baseService.getRespCityById(userInfoDetail.getAreaId());
            if (null != city && null != city.getName()){
                respUserCategoryList.setCity(city.getName());
            }
        }

        /**
         * 获取用户二维码
         */
        String userQRCode = baseService.getUserQRCode(userId);
        respUserCategoryList.setUserQRCode(userQRCode);
        myRedisTemplate.delteKey(redisKey);
        return APIResponse.returnSuccess(respUserCategoryList);
    }


    @Override
    public APIResponse setCategoryPriority(ReqCategoryPriorityList reqCategoryPriorityList) {
        if (null == reqCategoryPriorityList || reqCategoryPriorityList.getReqCategoryPriorityList().size() == 0 || null == reqCategoryPriorityList.getUid()){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        Integer uid = reqCategoryPriorityList.getUid();
        Integer changeNum = 0;
        for (ReqCategoryPriority reqCategoryPriority : reqCategoryPriorityList.getReqCategoryPriorityList()){
            CategoryPriority categoryPriority = new CategoryPriority();
            categoryPriority.setUid(uid);
            BeanUtils.copyProperties(reqCategoryPriority,categoryPriority);
            bizSportCardDao.setCategoryPriority(categoryPriority);
            changeNum++;
        }
        return APIResponse.returnSuccess(changeNum);
    }


    @Override
    public APIResponse<RespGameSportCardData> getSportCardData(Integer userId,Integer gameCategory) {
            if (null == userId || null == gameCategory || userId <= 0){
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
            }
            /**
             * 是否设置过运动水平
             **/
            RespGameSportCardData data = new RespGameSportCardData();
            boolean isSetted = this.isSetted(userId,gameCategory);
            data.setIsSetted(isSetted);
            data.setGameCategory(gameCategory);

            RespUserInfoDetail userInfoDetail = baseService.queryUserMsg(userId);
            if (null != userInfoDetail){
                /**
                 *  获取用户基本信息（名字，头像，性别）
                 */
                data.setUserName(userInfoDetail.getNickName());
                data.setIconUrl(userInfoDetail.getIcon());
                data.setSex(userInfoDetail.getGender().byteValue());

                /**
                 * 用户所在城市
                 */
                Integer areaId = userInfoDetail.getAreaId();
                RespCity city =  baseService.getRespCityById(areaId);
                if (null != city && null != city.getName()){
                    data.setCity(city.getName());
                }

                /**
                 *  获取个人比赛总场次、胜场数、胜率
                 */
                TbUserGameCollectExample example = new TbUserGameCollectExample();
                TbUserGameCollectExample.Criteria criteria = example.createCriteria();
                criteria.andGameCategoryIdEqualTo(gameCategory);
                criteria.andUidEqualTo(userId);
                List<TbUserGameCollect> tbUserGameCollectList = tbUserGameCollectMapper.selectByExample(example);
                if(null != tbUserGameCollectList && tbUserGameCollectList.size() > 0 ){
                    TbUserGameCollect userGameCollect = tbUserGameCollectList.get(0);
                    Float gameScheduleNum = userGameCollect.getGameScheduleNum().floatValue();
                    Float winGameScheduleNum = userGameCollect.getWinGameScheduleNum().floatValue();
                    Double winRate = 0.0;
                    if(gameScheduleNum > 0){
                        winRate = new Double(winGameScheduleNum/gameScheduleNum);
                    }
                data.setGameScheduleNum(gameScheduleNum.intValue());
                data.setWinGameScheduleNum(winGameScheduleNum.intValue());
                data.setWinRate(winRate);
            }


            /**
             * 个人城市排名、个人总积分、俱乐部排名
             */
            if (null != areaId){
                UserGrade userGrade= stadiumIndexService.getUserGrade(userId,gameCategory,areaId);
                data.setCityRaking(userGrade.getCityRaking());
                data.setTotalIntegral(userGrade.getTotalIntegral());
                data.setClubRaking(userGrade.getClubRaking());
            }
        }
        /**
         * 获取个人/团体等级信息
         */
        UserGradeIntegral userGradeIntegral = gradeIntegralService.getGradeInfo(userId, gameCategory);
        if (null != userGradeIntegral){
            data.setIntegral(userGradeIntegral.getIntegral());
            data.setGrade(userGradeIntegral.getGrade());
            data.setGradeIcon(userGradeIntegral.getGradeIcon());
        }

        return APIResponse.returnSuccess(data);
    }

    @Override
    public Boolean isSetted(Integer userId, Integer gameType) {
        ReqUserRadarChart reqUserRadarChart = new ReqUserRadarChart();
        reqUserRadarChart.setUid(userId);
        reqUserRadarChart.setType(gameType);
        Boolean isSetted = false;
        try {
             isSetted = radarChartService.checkRadarData(reqUserRadarChart).getData();
        }catch (Exception e){
            logger.error("雷达图服务不可用！");
        }
        return isSetted;
    }




    private List<TbGameCategoryUser> getGameCategoryUser(Integer userId){
        TbGameCategoryUserExample tbGameCategoryUserExample = new TbGameCategoryUserExample();
        TbGameCategoryUserExample.Criteria criteria = tbGameCategoryUserExample.createCriteria();
        criteria.andUidEqualTo(userId);
        return tbGameCategoryUserMapper.selectByExample(tbGameCategoryUserExample);
    }
}
